package org.jsola.hr.service.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.jsola.common.BeanKit;
import org.jsola.exception.ParamException;
import org.jsola.hr.service.IEmpSocTransformService;
import org.jsola.hr.vo.ImportSaveDateListResultVO;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.jsola.hr.constant.HrConstants.BATCH_PF;
import static org.jsola.hr.constant.HrConstants.BATCH_SOC;


/**
 * @author lyh
 */
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class BatchSocImportListener extends BaseAnalysisEventListener<Map<Integer, String>> {

    /**
     * 表头数据
     */
    private Map<Integer,String> allHeadMap;

    /**
     * 判断此次入库的是（社保和公积金）哪一种
     */
    private String type;

    /**
     * List最大盛装数据条数
     */
    private static final Integer MAX_COUNT = 2000;

    /**
     * 社保sheet导入结果
     */
    private ImportSaveDateListResultVO batchSocImportResult;

    /**
     * 公积金sheet导入结果
     */
    private ImportSaveDateListResultVO batchPfImportResult;

    /**
     * 参保月份Id
     */
    private String monthId;

    @Override
    public void saveData() {
        log.info("{}条数据，开始存储数据库！", dataList.size());
        if(CollectionUtils.isEmpty(dataList)){
            return;
        }
        ParamException.notNull(tokenUser, "没有设置当前登录用户");
        IEmpSocTransformService empSocTransformService = BeanKit.getBean(IEmpSocTransformService.class);
        if(BATCH_SOC.equals(type)){
        } else if(BATCH_PF.equals(type)){
        }
    }


    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        // 获取行的索引
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        dataList.add(data);
        if (dataList.size() >= MAX_COUNT) {
            // 入库
            saveData();
            // 存储完成清理 list
            dataList.clear();
        }
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        allHeadMap = headMap;

        // 验证EXCEL表头对应名称
        List<String> stringList = new ArrayList<>();
        stringList.add("身份证号*");
        stringList.add("姓名*");
        stringList.add("参保时间*");
        stringList.add("缴费类型（原因）*");

        List<String> excelHeadList = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : headMap.entrySet()) {
            excelHeadList.add(entry.getValue());
        }
        for (String headName : stringList) {
            if (!excelHeadList.contains(headName)) {
                if(BATCH_SOC.equals(type)){
                    throw new ParamException("导入的【社保sheet模板】不正确（请查看模板表头）");
                } else if(BATCH_PF.equals(type)){
                    throw new ParamException("导入的【医保sheet模板】不正确（请查看模板表头）");
                }

            }
        }

    }
}
